package com.example.web_chat.mapper;

import com.example.web_chat.model.*;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    //用户注册
    @Insert("insert into user(username, password) value(#{user.username}, #{user.password})")
    Integer insertUser( @Param("user") User user);
    //用户登录
    @Select("select * from user where username = #{username}")
    User selectUser(String username);

    //查询用户的好友
    @Select("select userId as friendId, username as friendName from user where userId in(select friendId from friend where userId=#{userId})")
    List<Friend> queryFriend(Integer userId);

    //通过userId查询会话
    @Select("select session_id from message_session where session_id in(select session_id from message_session_user where user_id = #{userId}) order by last_time desc")
    List<Integer> querySessionIdByUserId(Integer userId);

    //通过sessionId查询当前会话中有哪些好友
    @Select("select userId as friendId, username as friendName from user where userId in(select user_id from message_session_user where session_id = #{sessionId} and user_id != #{userId})")
    List<Friend>  queryFriendBySessionId(@Param("sessionId") Integer sessionId, @Param("userId") Integer userId);

    //向message_session表中插入新增的会话，并且返回自增主键
    @Options(useGeneratedKeys = true, keyProperty = "sessionId")
    @Insert("insert into message_session(last_time) value (now())")
    Integer insertSession(MessageSession messageSession);

    //向message_session_user表中插入数据
    @Insert("insert into message_session_user(session_id, user_id) value(#{sessionId}, #{userId})")
    Integer insertMessageSessionUser(@Param("sessionId") Integer sessionId,  @Param("userId") Integer userId);

    //根据sessionId获取最后一条消息
    @Select("select content from message where sessionId = #{sessionId} order by postTime desc limit 1")
    String getLastMessageBySessionId(Integer sessionId);

    //根据sessionId获取到当前会话中所有的消息
    @Select("select m.messageId, m.fromId, u.username as fromName, m.sessionId, m.content " +
            "from message m, user u " +
            "where m.fromId = u.userId and m.sessionId = #{sessionId} " +
            "order by postTime desc limit 100")
    List<Message> getAllMessageForSession(Integer sessionId);

    //通过message对象，将转发的消息保存在数据库中
    @Insert("insert into message(fromId, sessionId, content, postTime) " +
            "value(#{message.fromId}, #{message.sessionId}, #{message.content}, now())")
    Integer add(@Param("message") Message message);

}
